package com.magic.order.interceptor;

import com.magic.common.pojo.UserInfo;
import com.magic.common.utils.CookieUtils;
import com.magic.common.utils.JwtUtils;
import com.magic.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lan.jianyuan
 * @create 2021-02-17-11:01
 */
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtProperties jwtProperties;
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();
    
    public LoginInterceptor(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie中的token
        String cookieValue = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
        //解析token，获取用户信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(cookieValue, this.jwtProperties.getPublicKey());
        if (userInfo == null) {
            return false;
        }
        //把userInfo放入局部线程变量
        THREAD_LOCAL.set(userInfo);
        return true;
    }
    public static UserInfo getLoginUser() {
        return THREAD_LOCAL.get();
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空线程的局部变量。因为使用的是tomcat的线程池，线程不会结束，也就不会释放线程的的变量
        THREAD_LOCAL.remove();
    }
}
